﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace CKS.PLC.Action.System
{
    /// <summary>
    /// 自定义订阅数据点位动作类
    /// </summary>
    public class SubscriptionDataAction : PLCAction {
        
        public SubscriptionDataAction(DecodeValue value) : base(value) {
        }

        public override void Execute(Dictionary<string, object> execParams) {
            var actionKey = DecodeValue.Position.ActionKey;
            if (string.IsNullOrEmpty(actionKey)) {
                throw new InvalidOperationException($"Position：{DecodeValue.Position.BytePosition}，actionKey is not configured.");
            }
            
            // 获取当前程序集
            Assembly assembly = PlcActionDLLManage.GetActionAssembly();

            // 找出符合DecodeValue.Position.ActionKey条件的SubscribeActionAttribute特性类
            var typesWithAttribute = assembly.GetTypes()
                .Where(t => t.GetCustomAttributes(typeof(SubscribeActionAttribute), false)
                            .Cast<SubscribeActionAttribute>()
                            .Any(attr => attr.ActionKey == actionKey)
                ).ToList();

            // 如果没有找到，抛出异常
            if (typesWithAttribute.Count == 0) {
                throw new InvalidOperationException($"Position：{DecodeValue.Position.BytePosition}|ActionKey：{DecodeValue.Position.ActionKey}，executable actionKey subscription action class is not found.");
            }

            // 假设只找到一个符合条件的类
            Type actionType = typesWithAttribute.First();
            // 创建该类的实例
            SubscribeBase actionInstance = Activator.CreateInstance(actionType, DecodeValue) as SubscribeBase;
            //actionInstance.ExecuteBefor();
            actionInstance.Execute(execParams);
            //actionInstance.ExecuteAfter();
        }

    }
}
